package com.tticar.invmanager.common.utils;

import com.tticar.invmanager.common.exception.MyServiceException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * excel工具类
 *
 * @author jiwenbin
 * @createDate 2018-09-18
 */
public class ExcelUtils {

    private final static String excel_2003 = ".xls";    //2003- 版本的excel

    private final static String excel_2007 = ".xlsx";   //2007+ 版本的excel

    /**
     * 获取excel第一页
     *
     * @param excelFile excel文件
     * @param titles 表头（用于校验表头格式）
     * @return
     * @throws IOException
     */
    public static List<List<String>> getExcelSheet(MultipartFile excelFile, String[] titles) throws Exception {
        List<List<List<String>>> list = getExcelSheets(excelFile, titles);
        return list.get(0);
    }

    /**
     * 获取excel多页
     *
     * @param excelFile excel文件
     *  * @param titles 表头（用于校验表头格式）
     * @return
     * @throws IOException
     */
    public static  List<List<List<String>>> getExcelSheets(MultipartFile excelFile, String[] titles) throws Exception{
        if (excelFile == null || excelFile.getSize() <= 0) {
            throw new MyServiceException("上传文件不能为空");
        }
        return getListByExcel(excelFile.getInputStream(), excelFile.getOriginalFilename(), titles);
    }

    /**
     * 根据流获取excel数据list
     *
     * @param in
     * @param fileName
     * @param titles excel表头
     * @return
     * @throws IOException
     */
    public static List<List<List<String>>> getListByExcel(InputStream in, String fileName, String[] titles) throws Exception {

        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new MyServiceException("创建Excel工作薄为空！");
        }
        Sheet sheet = null;  //页
        Row row = null;  //行
        Cell cell = null;  //列

        List<List<List<String>>> list = new ArrayList<>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            // 校验表头
            checkExcelTemplet(sheet, titles);
            //遍历当前sheet中的所有行
            if (sheet.getLastRowNum() > 500) {
                throw new MyServiceException("Excel文件过大！请拆分为多个，每个最多500行");
            }
            List<List<String>> rowList = new ArrayList<>();
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }
                List<String> li = new ArrayList<>();
                //遍历所有的列
                for (int y = 0; y < sheet.getRow(0).getPhysicalNumberOfCells(); y++) {
                    cell = row.getCell(y);
                    li.add(getValue(cell));
                }
                rowList.add(li);
            }
            list.add(rowList);
        }
        return list;
    }

    /**
     * 根据文件后缀，自适应上传文件的版本
     *
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel_2003.equals(fileType)) {
            wb = new HSSFWorkbook(inStr);  //2003
        } else if (excel_2007.equals(fileType)) {
            wb = new XSSFWorkbook(inStr);  //2007
        } else {
            throw new MyServiceException("上传文件必须是excel(2003或2007版本)");
        }
        return wb;
    }

    /**
     * 对表格中数值进行格式化
     * @param cell
     * @return
     */
    public static String getValue(Cell cell) {
        String value = "";
        if (null == cell) {
            return value;
        }
        switch (cell.getCellType()) {
            //数值型
            case Cell.CELL_TYPE_NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //如果是date类型则 ，获取该cell的date值
                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    value = format.format(date);
                    ;
                } else {// 纯数字
                    BigDecimal big = new BigDecimal(cell.getNumericCellValue());
                    value = big.toString();
                    //解决1234.0  去掉后面的.0
                    if (null != value && !"".equals(value.trim())) {
                        String[] item = value.split("[.]");
                        if (1 < item.length && "0".equals(item[1])) {
                            value = item[0];
                        }
                    }
                }
                break;
            //字符串类型
            case Cell.CELL_TYPE_STRING:
                value = cell.getStringCellValue().toString();
                break;
            // 公式类型
            case Cell.CELL_TYPE_FORMULA:
                //读公式计算值
                value = String.valueOf(cell.getNumericCellValue());
                if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
                    value = cell.getStringCellValue().toString();
                }
                break;
            // 布尔类型
            case Cell.CELL_TYPE_BOOLEAN:
                value = " " + cell.getBooleanCellValue();
                break;
            default:
                value = cell.getStringCellValue().toString();
        }

        if ("null".endsWith(value.trim())) {
            value = "";
        }
        return value;
    }

    public static HSSFFont font;
    public static HSSFCellStyle style;
    public static HSSFCellStyle titleStyle;

    /**
     * 创建excel导入模板
     * */
    public static HSSFWorkbook createExcel(String[] titles) {
        // 创建Excel的工作书册 Workbook,对应到一个excel文档
        HSSFWorkbook wb = new HSSFWorkbook();
        // init(wb);
        // 创建Excel的工作sheet,对应到一个excel文档的tab
        HSSFSheet sheet = wb.createSheet("sheet1");
        // 创建Excel的sheet的一行
        HSSFRow row = sheet.createRow(0);
        // 创建一个Excel的单元格
        for (int i = 0; i < titles.length; i++) {
            HSSFCell cell = row.createCell(i);
            // 给Excel的单元格设置样式和赋值
            //cell.getCellStyle().cloneStyleFrom(style);
            cell.setCellStyle(style);
            cell.setCellValue(titles[i]);
        }
        return wb;
    }

    /**
     * 校验表头
     * @return
     */
    public static void checkExcelTemplet(Sheet sheet, String[] titles) {
        if (titles == null) {
            return;
        }
        List<String>  list = getExcelTitle(sheet);
        if (titles.length != list.size()) {
            throw new MyServiceException("导入excel格式有误，请下载最新模板");
        }
        for (int i=0; i<titles.length; i++) {
            if (!titles[i].trim().equals(list.get(i).trim())) {
                throw new MyServiceException("导入excel格式有误，请下载最新模板");
            }
        }
    }

    /**
     * 获取excel的表头
     * @param sheet
     * @return
     */
    public static List<String> getExcelTitle(Sheet sheet) {
        // 获取excel的表头
        List<String> list  = new ArrayList<>();
        Row row = sheet.getRow(0);
        int columnNum = row.getLastCellNum();
        for (int i=0; i<columnNum; i++) {
            list.add(row.getCell(i) == null ? "" : row.getCell(i).toString());
        }
        return list;
    }


}